package com.kuangstudy.service.zset;

import com.kuangstudy.entity.Content;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @description:
 * @author: xuke
 * @time: 2021/6/9 21:12
 */
@Service
@Slf4j
public class TaobaoService {

    @Autowired
    private RedisTemplate redisTemplate;


    // 步骤1：模拟直播间的数据
    @PostConstruct
    public void init() {
        log.info("淘宝直播间数据初始化...");
        new Thread(() -> {
            this.refreshData();
        }).start();
    }


    public void refreshOnlineRoom() {
        // 1: 弹幕容器
        List<Content> contentList = new ArrayList<>();
        // 2：直播间的房号
        String roomkey = "room:100";
        Random random = new Random();
        for (int i = 1; i <= 6; i++) {
            Content content = new Content();
            Integer userId = random.nextInt(10000);
            content.setUserId(userId);
            content.setNickname("jack" + userId);
            content.setContent("content" + random.nextInt(1000));
            long time = System.currentTimeMillis();
            content.setSendtime(time);
            contentList.add(content);
            this.redisTemplate.opsForZSet().add(roomkey, content, time / 1000);

            log.info("模拟直播间：" + roomkey + ",发言弹幕数据：{}", content);
        }

    }


    public void refreshData() {
        while (true) {
            this.refreshOnlineRoom();
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
}
